//
//  ShowAdvertisement.m
//  AdvertisementSDK
//
//  Created by APPYING on 14-7-21.
//  Copyright (c) 2014年 APPYING. All rights reserved.
//

#import "ShowAdvertisement.h"

@interface ShowAdvertisement ()

@end

@implementation ShowAdvertisement

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

/**
 *  显示广告的弹窗
 *
 *  @param appId 应用在AVOS上的id值
 *
 *  @return 弹窗视图
 */
- (UIView *)showAdvertisement:(NSString *)appId {
    //广告在AVOS上的key值
    [AVOSCloud setApplicationId:@"n6z0ikizwmfjeliynj7j3envrlwuiqmtgi1mycd7ipj2wozu"
                      clientKey:@"co5ui2h2jbagcwqdu2dgg79uoo6yt3om9ybjhx5hj60g2voz"];
    
    //广告图片最大的宽度和高度
    float imgMaxWidth = kScreen_Width - 20.0;
    float imgMaxHeight = kScreen_Height - 40.0;
    
    //用于计时操作，数据从AVOS上读取
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSDate *lastOpenTime = [accountDefaults objectForKey:@"lastOpenTime"];
    NSTimeInterval secondsBetweenDates= [[NSDate date] timeIntervalSinceDate:lastOpenTime];
    [accountDefaults setObject:[NSDate date] forKey:@"lastOpenTime"];
    
    //需要返回的广告视图
    returnView = [[UIView alloc] init];
    returnView.frame = CGRectMake(0, 0, 320, 568);
    returnView.backgroundColor = [UIColor clearColor];
    
    //进行AVOS上数据的查询
    AVQuery *query = [AVQuery queryWithClassName:@"app"];
    
    AVObject *app = [query getObjectWithId:appId];
    
    //如果当前打开应用时间在间隔时间内，则不显示广告
    int secondsAll = [[app objectForKey:@"step"] floatValue] * 60 * 60;
    if (secondsBetweenDates < secondsAll) {
        return nil;
    }
    
    //判断应用的广告是否处于激活状态
    if ([[app objectForKey:@"active"] intValue]) {
        AVRelation *relation = [app relationforKey:@"advertisements"];
        
        NSArray *objects = [[relation query] findObjects];
        if (objects.count > 0) {
            //进行广告数据的读取和展示
            AVObject *advertise = [objects firstObject];
            urlAdvertisement = [advertise objectForKey:@"target"];
            AVFile *advertiseImg = [advertise objectForKey:@"img"];
            //获取广告图片并存储到变量中
            UIImage *imageAd = [UIImage imageWithData:[advertiseImg getData]];
            advertiseImgView = [[UIImageView alloc] initWithImage:imageAd];
            
            //获取广告图片的宽度和高度，2倍图，除以2，而后进行广告图片大小的等比例转换
            float imageAdWidth = imageAd.size.width/2;
            float imageAdHeight = imageAd.size.height/2;
            float scale = 0;
            if (imageAdWidth > imgMaxWidth) {
                scale = imgMaxWidth / imageAdWidth;
                imageAdWidth = imgMaxWidth;
                imageAdHeight = imageAdHeight * scale;
            }
            if (imageAdHeight > imgMaxHeight) {
                scale = imgMaxHeight / imageAdHeight;
                imageAdHeight = imgMaxHeight;
                imageAdWidth = imageAdWidth * scale;
            }
            advertiseImgView.frame = CGRectMake((kScreen_Width - imageAdWidth)/2, 20 + (kScreen_Height - 15 - imageAdHeight)/2, imageAdWidth, imageAdHeight);
            
            advertiseImgView.userInteractionEnabled = YES;
            [returnView addSubview:advertiseImgView];
            UITapGestureRecognizer *singleTap =[[UITapGestureRecognizer alloc]init];
            [singleTap addTarget:_target action:@selector(onClickImage)];
            [advertiseImgView addGestureRecognizer:singleTap];
            
            //添加广告图片
            UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"removeAdImg" ofType:@"bundle"]] pathForResource:@"img_delete_advertisement" ofType:@"png"]];
            
            //去除广告按钮
            UIButton *removeAdvertisement = [[UIButton alloc] init];
            [removeAdvertisement setBackgroundImage:image forState:UIControlStateNormal];
            removeAdvertisement.frame = CGRectMake(advertiseImgView.frame.size.width - image.size.width/3, 0, image.size.width/3, image.size.height/3);
            [removeAdvertisement addTarget:_target action:@selector(removeAd:) forControlEvents:UIControlEventTouchUpInside];
            
            [advertiseImgView addSubview:removeAdvertisement];
        }
    return returnView;
    }
    return nil;
}

/**
 *  图片的点击事件
 */
- (void)onClickImage {
    if (urlAdvertisement != nil) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", urlAdvertisement]]];
        if (returnView != nil) {
            [returnView removeFromSuperview];
        }
    }
}

/**
 *  移除广告
 *
 *  @param sender 移除广告按钮
 */
- (void)removeAd:(UIButton *)sender {
    if (returnView != nil) {
        [returnView removeFromSuperview];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
